# -*- coding:utf-8 -*-

from flask import request, render_template, jsonify, session, g, current_app
from sqlalchemy.sql import or_
from app.models.application import Business_Application as BA, Purchase_Application as PA, Tracking
from app.models.business import Car
from app.models.account import User
from app import db
from app.tools.permission import permission
from app.tools.log import log
from app.tools.safe import safe_data
from flask_login import login_required
import datetime
from . import track


@track.before_request
@login_required
@permission(['service', 'director', 'admin', 'super'])
def check_permission():  # 检查权限
    g.kw = {}
    if session.get('role') == 'service':
        g.kw['tracker_id'] = session.get('sid')  # 客服只能看到分配给自己的单，其他角色可以看到全部
    return


@track.route('/buy/list/')
def buy_list():  # 返回购车申请列表的界面，列表数据由ajax异步获取
    return render_template('tracking/track/buy.html', title=u"购车申请")


@track.route('/buy/get_list/')
def get_buy_list():  # 获取购车申请的数据
    values = request.values
    limit = int(values.get('limit', '10'))
    offset = int(values.get('offset', '0'))
    list_type = values.get('list_type')
    number = values.get('number')
    start = values.get('start')
    end = values.get('end')
    submitter = values.get('submitter')
    area = values.get('area')
    search_type = values.get('search_type')
    tb_name = values.get('tb_name')  # 前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
    try:
        start = datetime.datetime.strptime(start, '%Y-%m-%d')
        end = datetime.datetime.strptime(end, '%Y-%m-%d')
        end = end + datetime.timedelta(days=1)  # 需要加一天才可以搜索到原本的end指定的日期
    except ValueError:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    if list_type is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    result = PA.query
    if tb_name == list_type and search_type != '5':  # 5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
        if search_type == '0':
            g.kw['number'] = number
        if search_type == '1' or search_type == '4':
            g.kw['application_type'] = submitter
        if search_type == '2' or search_type == '4':
            result = result.filter(PA.area.like('%' + area + '%'))
        if search_type == '3' or search_type == '4':
            result = result.filter(PA.submission_date.between(start, end))
    if list_type == 'valid':
        g.kw['outside'] = 0
        result = result.filter(or_(PA.state == 1, PA.state == 2))
    elif list_type == 'finish':
        g.kw['outside'] = 0
        result = result.filter(or_(PA.state == 3, PA.state == 4))
    elif list_type == 'outside':
        g.kw['outside'] = 1
    else:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    result = result.filter_by(**g.kw).order_by(db.desc(PA.submission_date)).paginate(offset / limit + 1, limit, False)
    count = result.total
    data = []
    states = {1: u'待跟进', 2: u'跟进中', 3: u'线下跟进', 4: u'已废弃'}
    for item in result.items:
        data.append({
            'number': item.number,
            'title': item.car_title,
            'name': item.name,
            'phone': item.phone,
            'time': item.finish_date.strftime(
                "%Y-%m-%d %H:%M:%S") if list_type == 'finish' else item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
            'area': item.area,
            'state': states[item.state],
            'operate': 'outside/?app_number=%s' % item.number if list_type == 'outside' else 'details/?app_number=%s&app_type=buy' % item.number
        })
    json = {'total': count, 'rows': data}
    return jsonify(json)


@track.route('/business/<btype>/list/')
def business_list(btype):
    titles = {'rent': u'租车申请', 'finance': u'金融申请', 'service': u'服务申请'}
    if btype not in titles:
        return render_template('404.html'), 404
    return render_template('tracking/track/business.html', title=titles[btype], btype=btype)


@track.route('/business/<btype>/get_list/')
def get_business_list(btype):  # 获取业务申请的数据
    if btype not in ['rent', 'finance', 'service']:
        return jsonify({'state': 1})
    values = request.values
    limit = int(values.get('limit', '10'))
    offset = int(values.get('offset', '0'))
    g.kw['application_type'] = btype
    number = values.get('number')
    start = values.get('start')
    end = values.get('end')
    submitter = values.get('submitter')
    area = values.get('area')
    search_type = values.get('search_type')
    tb_name = values.get('tb_name')  # 前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
    list_type = request.values.get('list_type')
    try:
        start = datetime.datetime.strptime(start, '%Y-%m-%d')
        end = datetime.datetime.strptime(end, '%Y-%m-%d')
        end = end + datetime.timedelta(days=1)  # 需要加一天才可以搜索到原本的end指定的日期
    except ValueError:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    if list_type is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    result = BA.query
    if tb_name == list_type and search_type != 5:  # 5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
        if search_type == '0':
            g.kw['number'] = number
        if search_type == '1' or search_type == '4':
            g.kw['application_type'] = submitter
        if search_type == '2' or search_type == '4':
            result = result.filter(BA.area.like('%' + area + '%'))
        if search_type == '3' or search_type == '4':
            result = result.filter(BA.submission_date.between(start, end))
    if list_type == 'valid':
        result = result.filter(or_(BA.state == 1, BA.state == 2))
    elif list_type == 'finish':
        result = result.filter(or_(BA.state == 3, BA.state == 4))
    else:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    result = result.filter_by(**g.kw).order_by(db.desc(BA.submission_date)).paginate(offset / limit + 1, limit, False)
    count = result.total
    data = []
    states = {1: u'待跟进', 2: u'跟进中', 3: u'线下跟进', 4: u'已废弃'}
    for item in result.items:
        data.append({
            'number': item.number,
            'title': item.product,
            'name': item.name,
            'phone': item.phone,
            'time': item.finish_date.strftime(
                "%Y-%m-%d %H:%M:%S") if list_type == 'finish' else item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
            'area': item.area,
            'state': states[item.state],
            'operate': '?app_number=%s&app_type=%s' % (item.number, btype),
        })
    json = {'total': count, 'rows': data}
    return jsonify(json)


@track.route('/details/')
def details():  # 申请详情
    app_number = request.values.get('app_number')
    app_type = request.values.get('app_type')
    if app_number is None or app_type is None:
        return render_template('404.html'), 404
    if app_type not in ['buy', 'rent', 'finance', 'service']:
        return render_template('404.html'), 404
    g.kw['number'] = app_number
    if app_type == 'buy':
        result = PA.query.filter_by(**g.kw).first()
    else:
        g.kw['application_type'] = app_type
        result = BA.query.filter_by(**g.kw).first()
    if result:
        records = Tracking.query.filter_by(aid=result.id, application_type=app_type).order_by(
            Tracking.time.desc()).all()  # 获取申请的跟进记录
        if app_type == 'buy':
            result.car_title = "<a target='_blank' href='%s/detail/%s.html'>%s</a>" % (
            current_app.config['FRONT_URL'], result.car_id, result.car_title)
        return render_template('tracking/track/detail.html', data=result, records=records, app_type=app_type)
    return render_template('404.html'), 404


@track.route('/outside/')
def outside():  # 非自营车辆的申请数据
    app_number = request.values.get('app_number')
    if app_number is None:
        return render_template('404.html'), 404
    result = PA.query.filter_by(number=app_number, outside=1).first()
    if result:
        car = Car.query.filter_by(id=result.car_id).first()
        if car:
            owner = User.query.filter_by(id=car.owner_id).first()
        if owner:
            result.car_title = "<a target='_blank' href='%s/detail/%s.html'>%s</a>" % (
            current_app.config['FRONT_URL'], result.car_id, result.car_title)
            return render_template('tracking/track/outside.html', data=result, owner=owner, car=car)
    return render_template('404.html'), 404


@track.route('/offline/', methods=['GET', 'POST'])
def offline():  # 将申请置为线下跟进
    app_number = request.values.get('app_number')
    app_type = request.values.get('app_type')
    if app_number is None or app_type is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    if app_type not in ['buy', 'rent', 'finance', 'service']:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    g.kw['number'] = app_number
    if app_type == 'buy':
        result = PA.query.filter_by(**g.kw).filter(or_(PA.state == 1, PA.state == 2)).first()
    else:
        g.kw['application_type'] = app_type
        result = BA.query.filter_by(**g.kw).filter(or_(BA.state == 1, BA.state == 2)).first()
    if result:
        result.state = 3  # 线下跟进
        result.finish_date = datetime.datetime.now()
        result.save()
        log(u'将申请%s置为线下跟进' % result.number)
        return jsonify({'state': 0})
    return jsonify({'state': 2, 'msg': u'对象不存在'})


@track.route('/abandon/', methods=['GET', 'POST'])
def abandon():  # 废弃申请
    app_number = request.values.get('app_number')
    app_type = request.values.get('app_type')
    if app_number is None or app_type is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    if app_type not in ['buy', 'rent', 'finance', 'service']:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    g.kw['number'] = app_number
    if app_type == 'buy':
        result = PA.query.filter_by(**g.kw).filter(or_(PA.state == 1, PA.state == 2)).first()
    else:
        g.kw['application_type'] = app_type
        result = BA.query.filter_by(**g.kw).filter(or_(BA.state == 1, BA.state == 2)).first()
    if result:
        result.state = 4
        result.finish_date = datetime.datetime.now()
        result.save()
        log(u'废弃申请%s' % result.number)
        return jsonify({'state': 0})
    return jsonify({'state': 2, 'msg': u'对象不存在'})


@track.route('/add_tracking/', methods=['GET', 'POST'])
def add_tracking():  # 添加跟进记录
    app_number = request.values.get('app_number')
    app_type = request.values.get('app_type')
    content = request.values.get('content')
    if app_number is None or app_type is None or content is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    if app_type not in ['buy', 'rent', 'finance', 'service']:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    if content == '':
        return jsonify({'state': -1, 'msg': u'请填写跟进内容'})
    g.kw['number'] = app_number
    if app_type == 'buy':
        result = PA.query.filter_by(**g.kw).filter(or_(PA.state == 1, PA.state == 2)).first()
    else:
        g.kw['application_type'] = app_type
        result = BA.query.filter_by(**g.kw).filter(or_(BA.state == 1, BA.state == 2)).first()
    if not result:
        return jsonify({'state': 2, 'msg': u'对象不存在'})
    record = Tracking(application_type=app_type, aid=result.id, tracker_id=session.get('sid'),
                      tracker_name=session.get('name'), content=safe_data(content), time=datetime.datetime.now())
    record.save()
    log(u'为申请%s添加跟进记录' % result.number)
    if result.state == 1:  # 如果是待跟进状态，则修改为跟进中
        result.state = 2
        result.save()
    return jsonify({'state': 0})
